<template>
  <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="formRules"
      size="small"
      :inline="false"
      label-width="100px"
    >
      <el-form-item label="主题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入主题"
          maxlength="32"
          size="small"
        />
      </el-form-item>
      <el-form-item label="候选人" prop="candidateId">
        <el-select
          v-model="formData.candidateId"
          placeholder="请选择候选人"
          size="small"
          filterable
        >
          <el-option
            v-for="item in candidateList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="沟通时间" prop="actionStartTime">
        <div style="max-width: 400px">
        <el-date-picker
          v-if="dateType"
          v-model="formData.actionStartTime"
          :default-value="new Date()"
          type="datetime"
          placeholder="请选择"
          size="small"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="changeTime"
        />
        <el-date-picker
            v-else
            v-model="formData.actionStartTime"
            type="datetime"
            style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择"
        />
        </div>
        <el-button style="margin-left: 10px" plain :icon="Refresh" @click="dateType = !dateType"/>
      </el-form-item>
      <el-form-item label="优先度">
        <el-radio-group v-model="formData.priority">
          <el-radio :label="0" size="small">普通</el-radio>
          <el-radio :label="1" size="small">高</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="通知时间" prop="remindState">
        <el-radio-group v-model="formData.remindState">
          <el-radio
            v-for="item in remindTimes"
            :key="item.value"
            :label="item.value"
            size="small"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="通知方式" prop="remindType">
        <el-checkbox-group v-model="formData.remindType" size="small">
          <el-checkbox label="1">应用、公众号通知</el-checkbox>
          <el-checkbox label="2">短信通知</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
</template>

<script>
// 候选人offer前沟通  OA_OFFER_INTERACT
import { onMounted, reactive, toRefs ,ref, watch, nextTick} from "vue";
import { getListByType } from "/@/api/oa/candidate";
import { getRemindTimes } from "/@/api/matter";
import { formatDate } from "/@/utils/formatTime";
// import {getRemindTimes} from '/@/api/matter'
import { homeApi } from "/@/api/home/index";
import {Refresh} from '@element-plus/icons-vue'
import { format } from "/@/views/home/component/lib/utils";
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';

export default {
    name: 'InteractPreOfferForm',
    props: {
        selectTime: {
            type: String,
            default: null
        },
        editId: {
          type: String,
          default: null
        }
    },
    setup(props, context) {
        const { editId, selectTime } = toRefs(props)
        const homeCalendar = homeApi();
        const ruleFormRef = ref({});
        const storesCalendarConfig = useCalendarConfig();
        const { eventForm } = storeToRefs(storesCalendarConfig)
        const state = reactive({
            formData: {
                candidateId: null,
                title: "Offer前沟通",
                actionStartTime: selectTime.value ? selectTime.value : formatDate(new Date(), "YYYY-mm-dd HH:MM:SS"), // 行动时间（沟通时间）
                remindState: "NONE", // 提醒时间, 根据枚举类MatterRemindTimeEnum
                remindType: [], // 提醒方式, 多选
                state: 2, // 状态 -1草稿 0未开始 1进行中 2已完成 3已退回  4已取消 5已撤回
                priority: 0, // 优先级 0普通 1重要
            },
            dateType: true,   // 行动时间类型 true时间范围 false单时间
            candidateList: [],
            remindTimes: [],
            originForm: {}
        });
        const formRules = reactive({
            candidateId: { required: true, message: "请选择候选人", trigger: "change" },
            title: { required: true, message: "请填写主题", trigger: "blur" },
        });
        let close = () => {
            context.emit("ChiShaiormClose");
            reset();
         };

        let submit = () => {
            if (!ruleFormRef) return;
            return new Promise(async (resolve, reject) => {
                await ruleFormRef.value.validate((valid, fields) => {
                    if (valid) {
                        // console.log(state.formData);
                        if(editId.value) {
                          // 编辑
                          for(let key in state.formData){
                            if(state.originForm.hasOwnProperty(key)){
                              state.originForm[key] = state.formData[key]
                            }
                            if(state.originForm.info.hasOwnProperty(key)){
                              state.originForm.info[key] = state.formData[key]
                            }
                          }
                          storesCalendarConfig.setEventForm(state.originForm)
                          reset()
                          close()
                          resolve('edit') 
                        }else{
                          homeCalendar.addPreOfferInteract(state.formData).then((res) => {
                            if (res.code === 0) {
                              reset();
                              close();
                              resolve()
                            }else{
                              reject()
                            }
                          });
                        }
                    } else {
                        reject()
                        console.log("error submit!", fields);
                    }
                });
            })
        };

        const reset = () => {
            if (!ruleFormRef) return;
            ruleFormRef.value.resetFields();
        }
        const changeTime = (val) => {
            if (val) {
                let nowTime = new Date().getTime();
                let selectTime = new Date(val).getTime();
                // 如果现在时间小于选择时间 未开始状态
                if (nowTime < selectTime) {
                    state.formData.state = 0;
                } else {
                // 大于或等于都视为已完成
                    state.formData.state = 2;
                }
            }
        };
        watch(() => eventForm.value,
          val => {
            if(editId.value && val) {
              // 编辑
              nextTick(() => {
                const data = val
                if(!data) return
                state.originForm = data
                for(let params in data.info){
                  // 拿出info里面的数据
                  if(state.formData.hasOwnProperty(params)) {
                    state.formData[params] = data.info[params]
                  }
                }
                for(let key in data) {
                  // 列表里面的数据
                  if(state.formData.hasOwnProperty(key)) {
                    state.formData[key]= data[key]
                  }
                }
                if(data.remindType){
                  state.formData.remindType = data.remindType.split(',')
                }
              })
            }
          }        
        )
        onMounted(() => {
            try {
                getRemindTimes().then(res => state.remindTimes = res.data)
                // 获取面试通过的
                getListByType("4").then(res => state.candidateList = res.data)
            } catch (e) {
                console.log(e)
            }
        });
        return {
            ...toRefs(state),
            changeTime,
            submit,
            close,
            formRules,
            ruleFormRef,
            reset,
            Refresh
         };
    }
}
</script>

<style>

</style>